package cn.edu.buaa.nlsde.grid.DatabaseManage;

import java.sql.*;

import cn.edu.buaa.nlsde.grid.DatabaseConnect.*;
import cn.edu.buaa.nlsde.grid.Structure.Host;

public class MetricDiskManage
{
	DBConn db=null;
	DBPool dbpool=null;
	Statement stat=null;
	
	public MetricDiskManage(DBConn db)
	{
		this.db=db;
	}
	public MetricDiskManage(DBPool dbpool)
	{
		this.dbpool=dbpool;
	}
	
	public ResultSet getData(int HostID)
	{
		String sql="select * from Metric_Disk where HostID="+HostID+" order by CollectTime desc LIMIT 1";
		//System.out.println(sql);
		try
		{
			stat=dbpool.connect();
			ResultSet rs=stat.executeQuery(sql);
			return rs;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}

	public ResultSet getData(int HostID,String start,String end)
	{
		String sql="select * from Metric_Disk where CollectTime>'"+start+"' and CollectTime<'"+end+"' and HostID="+HostID+" order by collectTime asc";
		System.out.println(sql);
		try
		{
			stat=dbpool.connect();
			ResultSet rs=stat.executeQuery(sql);
			return rs;
		}
		catch(Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
	
	public String addRecord(int HostID,Host host,String collectTime)
	{
		double disk_free=Double.parseDouble(host.getMetric("disk_free"));
		double disk_total=Double.parseDouble(host.getMetric("disk_total"));
		String sql="insert into Metric_Disk (HostID,disk_total,disk_free,CollectTime) values ("+HostID+","+disk_total+","+disk_free+",'"+collectTime+"')";
		System.out.println(sql);
		
		try
		{
			stat=dbpool.connect();
			stat.executeUpdate(sql);
			return "Success";
		}
		catch(Exception e)
		{
			return "Fail";
		}
	}

	public String deleteRecord(int HostID)
	{
		String sql="delete from Metric_Disk where HostID="+HostID;
		try
		{
			stat=dbpool.connect();
			stat.executeUpdate(sql);
			return "Success";
		}
		catch(Exception e)
		{
			return "Fail";
		}
	}
	
	public String deleteRecord(String start,String end)
	{
		String sql="delete from Metric_Disk where CollectTime>'"+start+"' and CollectTime<'"+end+"'";
		System.out.println(sql);
		try
		{
			stat=dbpool.connect();
			stat.executeUpdate(sql);
			return "Success";
		}
		catch(Exception e)
		{
			return "Fail";
		}
	}
	
	public void close() throws SQLException
	{
		dbpool.close();
	}
}
